﻿/*
 * 
 * 
 * 
 *                 //#region OldDummyTestCode
                //uint retryOrder = 0;

                //// Main run: Place orders
                //// this is just test code
                //// This whole code will go into each stock's worker thread
                //while (retryOrder > 0)
                //{
                //    // Main Buy/Sell logic

                //    ////////////////////////////////
                //    // ** GET EQUITY QUOTES **   //
                //    //////////////////////////////

                //    //EquityStockQuote[] stockPrice = iciciDirectAccount.GetEquityQuote("INDBUL");

                //    //foreach (EquityStockTradeStats stockInfo in iciciDirectAccount.mStocksInSystem)
                //    //{
                //    //EquityStockTradeStats stockInfo = new EquityStockTradeStats("INDBUL", 1800, 49, Exchange.NSE, 100, 0.01, 35);
                //    //EquityStockQuote[] stockPrice = iciciDirectAccount.GetEquityQuote(stockInfo.StockCode);
                //    //if (stockPrice != null)
                //    //{
                //    //    stockInfo.AddOrUpdateStockPriceInExchange((EquityStockQuote)stockPrice[0]);
                //    //    stockInfo.AddOrUpdateStockPriceInExchange((EquityStockQuote)stockPrice[1]);
                //    //}
                //    //}
                //    ////////////////////////////////
                //    // ** PLACE EQUITY ORDERS ** //
                //    //////////////////////////////
                //    //errorCode = iciciDirectAccount.PlaceEquityMarginOrder("RELPOW", 25, "151", "142", OrderDirection.BUY);
                //    //errorCode = iciciDirectAccount.PlaceEquityDeliveryOrder("RELPOW", 20, "111", OrderPriceType.LIMIT, OrderDirection.BUY, Exchange.NSE);

                //    //Thread.Sleep(1000 * 60 * 10);

                //    List<EquityOrderRecord> orders = new List<EquityOrderRecord>();

                //    orders.Add(new EquityOrderRecord("INDBUL", 20, "102", OrderPriceType.LIMIT, OrderDirection.SELL, Exchange.NSE, EquityOrderType.DELIVERY, "0", "0"));
                //    //orders.Add(new EquityOrderRecord("INDBUL", 15, "110", OrderPriceType.LIMIT, OrderDirection.BUY, Exchange.NSE, EquityOrderType.DELIVERY, "0", "0"));
                //    //orders.Add(new EquityOrderRecord("IBSECU", 100, "24", OrderPriceType.LIMIT, OrderDirection.SELL, Exchange.NSE, EquityOrderType.DELIVERY, "0", "0"));
                //    //orders.Add(new EquityOrderRecord("CELLAB", 100, "18.5", OrderPriceType.LIMIT, OrderDirection.SELL, Exchange.BSE, EquityOrderType.DELIVERY, "0", "0"));
                //    //orders.Add(new EquityOrderRecord("UNITEC", 250, "52.55", OrderPriceType.LIMIT, OrderDirection.SELL, Exchange.NSE, EquityOrderType.DELIVERY, "0", "0"));
                //    //orders.Add(new EquityOrderRecord("UNITEC", 250, "40.05", OrderPriceType.LIMIT, OrderDirection.BUY, Exchange.NSE, EquityOrderType.DELIVERY, "0", "0"));
                //    //orders.Add(new EquityOrderRecord("UNITEC", 65, "44.05", OrderPriceType.LIMIT, OrderDirection.BUY, Exchange.NSE, EquityOrderType.DELIVERY, "0", "0"));
                //    List<BrokerErrorCode> errorCodes = null;

                //    errorCodes = iciciDirectAccount.PlaceMultipleEquityOrders(orders, 5);
                //    //int s = 0;
                //    //for (; s < errorCodes.Count; s++)
                //    //{
                //    //    if (errorCodes[s] == BrokerErrorCode.Success)
                //    //    {
                //    //        break;
                //    //    }
                //    //    if (errorCodes[s] == BrokerErrorCode.NotLoggedIn)
                //    //    {
                //    //        iciciDirectAccount.LogIn();
                //    //        break;
                //    //    }
                //    //}
                //    //if (errorCodes[s] == BrokerErrorCode.Success)
                //    //{
                //    //    break;
                //    //}

                //    // Single equity order
                //    // errorCode = iciciDirectAccount.PlaceEquityDeliveryOrder("RELPOW", 20, "111", OrderPriceType.LIMIT, OrderDirection.BUY, Exchange.NSE);
                //    ////////////////////////////////
                //    // ** REFRESH STOCK STATE ** //
                //    //////////////////////////////

                //    //errorCode = iciciDirectAccount.RefreshEquityStockStateToday(stockInfo);


                //    ///////////////////////////
                //    // ** GET ORDER BOOK ** //
                //    /////////////////////////

                //    //List<EquityOrderBookRecord> eq = iciciDirectAccount.GetEquityOrderBook(DateTime.Now, DateTime.Now.AddDays(1), false);

                //    //if (eq.Count < 1)
                //    //    continue;
                //    Thread.Sleep(1000 * 60 * 2);

                //    //////////////////////////
                //    // ** CANCEL ORDERS ** //
                //    ////////////////////////
                //    Dictionary<string, BrokerErrorCode> cancelOrderErrCodes;
                //    errorCode = iciciDirectAccount.//CancelEquityOrder("20081114N500004277", true, false);//
                //    CancelAllOutstandingEquityOrders(out cancelOrderErrCodes);


                //    //////////////////////////
                //    // ** MODIFY ORDER **  //
                //    ////////////////////////


                //    //bool modify = iciciDirectAccount.ModifyEquityOrder("20081117N500001292", true, true);




                //    retryOrder--;
                //}
                //#endregion
 * 
 *                 #region SimpleBuySellPairSquareAlgo

                //bool bCancelPairOrder= false;

                //// refresh stock state
                //errorCode = iciciAccount.RefreshEquityStockStateToday(stockInfo);
                //traceString = "RefreshEquityStockStateToday: " + errorCode.ToString();
                //FileTracing.TraceOut(traceString);

                //if (errorCode.Equals(BrokerErrorCode.Success))
                //{
                //    // If no buy or sell order pending, i.e. the square-off pair orders have executed
                //    // then place a pair of fresh buy-sell orders
                    
                //    if (!(stockInfo.IsAnyOutstandingBuyOrder() ||
                //        stockInfo.IsAnyOutstandingSellOrder()
                //        ))
                //    {
                //        // Place buy-sell order pair

                //        // Generate orders
                //        List<EquityOrderRecord> generatedOrders = new List<EquityOrderRecord>();

                //        string BidPrice;
                //        string OfferPrice;
                                 
                //        // price decision

                //        // Get latest quote
                //        EquityStockQuote[] stockPrice = iciciAccount.GetEquityQuote(stockCode);

                //        // First orders, only if market not open and it is first order pair
                //        if ((stockInfo.NumTrades == 0) && !MarketUtils.IsMarketOpen())
                //        {
                //            double closePrice = stockPrice[0].PreviousClosePriceDouble;

                //            decimal buy =  (decimal)(closePrice - ((double)(3.0/100) * closePrice));//prevclose - 3%
                //            buy = decimal.Subtract(buy, 0.05M);
                //            buy = decimal.Round(buy, 1);
                //            BidPrice = buy.ToString();     
                                                     
                //            decimal sell =  (decimal)(closePrice + ((double)(3.0/100) * closePrice));//prevclose + 3%
                //            sell = decimal.Add(sell, 0.05M);
                //            sell = decimal.Round(sell, 1, MidpointRounding.AwayFromZero);
                //            OfferPrice = sell.ToString();     

                //        }
                //            // Subsequent orders
                //            // TODO: May put time conditions or market volatility conditions here in else if
                //        else
                //        {
                //            double ltp = stockPrice[0].LastTradePriceDouble;

                //            decimal buy = (decimal)(ltp - ((double)(0.65 / 100) * ltp));//prevclose - 0.65%
                //            buy = decimal.Subtract(buy, 0.05M);
                //            buy = decimal.Round(buy, 1);
                //            BidPrice = buy.ToString();

                //            decimal sell = (decimal)(ltp + ((double)(0.65 / 100) * ltp));//prevclose + 0.65%
                //            sell = decimal.Add(sell, 0.05M);
                //            sell = decimal.Round(sell, 1, MidpointRounding.AwayFromZero);
                //            OfferPrice = sell.ToString();     
                //        }

                //        // Buy
                //        generatedOrders.Add(new EquityOrderRecord(stockInfo.StockCode, stockTradingLot, BidPrice, OrderPriceType.LIMIT, OrderDirection.BUY, stockInfo.MainExchange, EquityOrderType.DELIVERY, "0", "0"));
                //        // Sell
                //        generatedOrders.Add(new EquityOrderRecord(stockInfo.StockCode, stockTradingLot, OfferPrice, OrderPriceType.LIMIT, OrderDirection.SELL, stockInfo.MainExchange, EquityOrderType.DELIVERY, "0", "0"));
                        
                //        List<BrokerErrorCode> errorCodes = null;

                //        // Validate orders
                //        List<EquityOrderRecord> ordersToPlace = stockInfo.ReturnFilteredValidOrders(generatedOrders);


                //        // Place validated orders

                //        errorCodes = iciciAccount.PlaceMultipleEquityOrders(ordersToPlace, 5);

                //        traceString = "Stock: " + stockInfo.StockCode + " :PlaceMultipleEquityOrders: \n";
                //        int o = 0;
                //        foreach (BrokerErrorCode errCodeEach in errorCodes)
                //        {
                //            EquityOrderRecord order = ordersToPlace[o++];
                //            traceString = traceString + order.OrderDirection.ToString() + "-" + order.Quantity.ToString() +
                //                " at " + order.Price + ": " + errCodeEach.ToString() + "\n";

                //            // Place Order failed
                //            if(!errCodeEach.Equals(BrokerErrorCode.Success))
                //            {
                //                // Cancel both the orders
                //                bCancelPairOrder = true;
                //            }
                //        }
                //        FileTracing.TraceOut(traceString);

                //        // Even if any one of the orders failed to place, cancel the pair 
                //        if(bCancelPairOrder)
                //        {
                //            errorCode = IciciUtils.CancelStockOutstandingOrdersAndTrace(stockCode, iciciAccount);
                //        }
                //    }
                //}
                //// sleep of 60 seconds
                //Thread.Sleep(1000 * 60);

                #endregion

 * 
 * 
 *         //////////////////////////////////////
    //////      MODIFY ORDER       //////
    ////////////////////////////////////                      
    // TODO: correct it, not working now
    public BrokerErrorCode ModifyEquityOrder(string orderRef, bool refreshOrderBook, bool bDoLoginCheck)
    {

        // Login If needed
        BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);
        if (errorCode != BrokerErrorCode.Success)
        {
            return errorCode;
        }

        bool IsLoggedIn = false;

        if (refreshOrderBook)
        {
            // Make sure we have the latest order book data
            GetEquityOrderBookToday(false);
        }

        EquityOrderBookRecord eqOrderInfo;
        // Search for order in the Orders dictionary
        lock (lockObjectEquity)
        {
            if (mEquityOrderBook.ContainsKey(orderRef))
            {
                eqOrderInfo = mEquityOrderBook[orderRef];
            }
            else
            {
                throw new Exception("ModifyEquityOrder: Input OrderRef does not exist");
            }
        }


        // Instead of getting it actually from order book
        // We simply assume current day only
        DateTime currentDate = MarketUtils.GetMarketCurrentDate();
        string orderStatus = IciciUtils.EquityOrderStatusString[(int)eqOrderInfo.Status];
        string zipCode = orderRef.Substring(8, 2);

        string postData = //"FML_PASS=1" +
            "&FML_STATUS=" + orderStatus +
            "&FML_ORDR_RFRNC=" + orderRef +
            // TODO: C for CASH , currently hardcoded. needs to be handled. 
            // Get it in order book stock info somehow
            "&FML_XCHNG_ST=" + (string)(MarketUtils.IsMarketOpen() ? "Open" : "Closed") +
            "&FML_ORD_PRDCT_TYP=C" +
            "&FML_USR_ZIP_CD=" + zipCode + // N5 
            "&check=" +
            "&FML_TRN_PRDT_TYP=O" +
            "&FML_ORD_ORDR_FLW=" + IciciUtils.OrderDirectionString[(int)eqOrderInfo.Direction] + // order direction S/B
            "&FML_ACCOUNT=" + ACCOUNTNUM +
            "&FML_XCHNG_CD=" + IciciUtils.ExchangeString[(int)eqOrderInfo.Exchange] + // get exchange
            "&FML_ORD_XCHNG_CD=" + IciciUtils.ExchangeString[(int)eqOrderInfo.Exchange] + // get exchange
            "&FML_ORD_TRD_DT=" + // TODO: Use month name calculation , currently hardcoded "Nov"
            currentDate.ToString("dd") + "-" + currentDate.ToString("MMM") + "-" + currentDate.ToString("yyyy") +
            "&NicValue=" + "&x=" + "&check=";

        //"&FML_TO_DT=" +
        //toDate.ToString("dd") + "%2F" + toDate.ToString("MM") + "%2F" + toDate.ToString("yyyy") +
        //"&STCK_CD=All" +
        //"&FML_XCHNG_CD=A" +
        //"&PRDCT_TYPE=A" +
        //"&FML_ORDR_ST=A" +
        //"&FML_ORDR_ACTION=A&Submit=+View+" +
        //"&FML_FOCUS_FLAG=D" +
        //"&FML_TMP_FRM_DT=" + tmpDateToday +
        //"&FML_TMP_TO_DT=" + tmpDateToday +
        //"&FML_ORD_PRDCT_TYP=A" +
        //"&FML_strfinal=" + tmpDateLater +
        //"&FML_ORDR_RFRNC=" + "&FML_ORDR_FLW=" +
        //"&FML_TMP_STTLMNT_NMBR=" +
        //"&FML_STCK_CD=" +
        ////"&FML_SESSION_ID=" + FML_SESSION_ID +
        //"&FML_ORD_DP_ID=" + "&FML_CLNT_ID=" + "&Update=" + "&ButtonDis=" + "&x=" + "&HideLayer=";
    //https://secure.icicidirect.com/trading/equity/trading_modify_order.asp
   //https://secure.icicidirect.com/trading/equity/trading_modify_verifyorder.asp

        string modifyOrderData = IciciGetWebPageResponse("https://secure.icicidirect.com/trading/equity/trading_modify_verifyorder.asp",
            postData,
            null,
            mCookieContainer,
            out IsLoggedIn);

        if (!IsLoggedIn)
        {
            return BrokerErrorCode.NotLoggedIn;
        }
        string modifyFirstMsg = "Your request for Order Modification has been accepted by us";

        // 1st phase - Success
        if (modifyOrderData.Contains(modifyFirstMsg))
        {


        }

        string finalData = "aa";

        string modifyConfirm = "Your request for Order Modification has been accepted by us";
        if(finalData.Contains(modifyConfirm))
        {
            //// Delete the orderRef from mEquityOrderBook
            //lock (lockObjectEquity)
            //{
            //    mEquityOrderBook.Remove(orderRef);
            //}
            return errorCode;
        }

        return errorCode;
    }

iciciDirectAccount.GetDerivativesTradeBook(DateTime.Now, DateTime.Now, InstrumentType.FutureIndex, true);

Algo2_BuySellAnalyzer bsa = new Algo2_BuySellAnalyzer(

    percChangeForMarketDirection, //perc change for market direction

    stopLossPerc, //stop loss percentage
    minProfitPerc, //minimum profit percentage

    allowShort, //Short Sell Allowed?
    allowLong, //Long Position Allowed

    initialOrder, //Initial Order

    iciciDirectAccount,
    stockCode,
    tradeQuantity,
    instType,
    expiryDate

    );
 * 
 * */
/*
//Simulation
bsa.AddTick(new DerivativeQuoteInformation(5200/3.5, 5200/3.5, 5200/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5210/3.5, 5210/3.5, 5210/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5200/3.5, 5200/3.5, 5200/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5235/3.5, 5235/3.5, 5235/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5248/3.5, 5248/3.5, 5248/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5260/3.5, 5260/3.5, 5260/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5250/3.5, 5250/3.5, 5250/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5260/3.5, 5260/3.5, 5260/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5250/3.5, 5250/3.5, 5250/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5260/3.5, 5260/3.5, 5260/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5260/3.5, 5260/3.5, 5260/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5300/3.5, 5300/3.5, 5300/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5280/3.5, 5280/3.5, 5280/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5260/3.5, 5260/3.5, 5260/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5280/3.5, 5280/3.5, 5280/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5300/3.5, 5300/3.5, 5300/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5310/3.5, 5310/3.5, 5310/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5260/3.5, 5260/3.5, 5260/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5270/3.5, 5270/3.5, 5270/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5280/3.5, 5280/3.5, 5280/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5300/3.5, 5300/3.5, 5300/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5350/3.5, 5350/3.5, 5350/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5380/3.5, 5380/3.5, 5380/3.5));
bsa.AddTick(new DerivativeQuoteInformation(5370/3.5, 5370/3.5, 5370/3.5));
bsa.MarketClosing();
*/
    /*
    while (MarketUtils.IsMarketOpen())
    {
        DerivativeQuoteInformation di = iciciDirectAccount.GetDerivativeQuote(stockCode,
            instType,
            expiryDate);
        if (di != null)
        {
            bsa.AddTick(di);
            Thread.Sleep(50);
        }
        else
        {
            errorCode = iciciDirectAccount.LogIn();
            if (errorCode != BrokerErrorCode.Success)
            {
                throw new Exception("LogIn(). BrokerErrorCode=" + errorCode.ToString());
            }
        }
    }
     * */

//string url  = NSEParser.FindContractUrl("NIFTY", "28FEB2008", DerivativeType.Future, SymbolType.Index);
//NSEDerivativeInformation inf = NSEParser.GetSingleDerivativeInformation(url);

/*
using (FileStream stream = new FileStream("Input3.txt", FileMode.Open, FileAccess.Read))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        pageData = reader.ReadToEnd();
    }
}
*/

/*
XmlDocument doc = GeneralParser.GetStockList();
doc.Save("C:\\moneycontrolstocklist.xml");
*/

/*
MoneyControlParser.Parser.GetStockInfo(
    "ABC", "http://www.moneycontrol.com/india/stockpricequote/engineering/abg-infralogistics/00/15/ABG02"
    //"http://www.moneycontrol.com/india/stockpricequote/pharmaceuticals/aarti-drugs/00/15/AD"
    //"http://www.moneycontrol.com/india/stockpricequote/finance-leasinghire-purchase/a-k-s-credits/00/15/AKS"
    //"http://www.moneycontrol.com/india/stockpricequote/textiles-denim/arvind-mills/17/50/AM"
    );
*/

/*
MoneyControlParser.MoneyControlParser.GetStockListAndStoreInDatabase(ConnectionString);
MoneyControlParser.MoneyControlParser.UpdateStockData(ConnectionString);
*/

//NSEParser.UpdateHistoricalInformationForMoneyControlStockList(ConnectionString, DateTime.Now.AddDays(-35), DateTime.Now);
//NSEParser.PreProcessHistoricalInformationForMoneyControlStockList(10, ConnectionString);
/*
List<ErrorCode> succesCodes = null;
ICICIDirectAccount account = new ICICIDirectAccount("username", "password");
ErrorCode successCode = account.LogIn();
if (successCode == ErrorCode.Success)
{
    succesCodes = null;
    List<EquityOrderRecord> orders = new List<EquityOrderRecord>();

    //orders.Add(new EquityOrderRecord("ICIBAN", 50, "0", OrderPriceType.Market, OrderDirection.Buy, Exchange.NSE));

    succesCodes = account.PlaceMultipleEquityOrders(orders, int.MaxValue);
}
else
{
}
account.LogOut();
*/

/*
DateTime expiryDate = DateTime.ParseExact(ConfigurationManager.AppSettings["BuySellAnalyzer_Expiry"], "yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
FileTracing.TraceOut("ExpiryDate = " + expiryDate.ToLongDateString());
string stockCode = ConfigurationManager.AppSettings["BuySellAnalyzer_StockCode"];
FileTracing.TraceOut("StockCode = " + stockCode);
InstrumentType instType = (InstrumentType)Enum.Parse(typeof(InstrumentType), ConfigurationManager.AppSettings["BuySellAnalyzer_Instrument"]);
FileTracing.TraceOut("InstrumentType = " + instType);
int tradeQuantity = int.Parse(ConfigurationManager.AppSettings["BuySellAnalyzer_Quantity"]);
FileTracing.TraceOut("TradeQuantity = " + tradeQuantity);
double percChangeForMarketDirection = double.Parse(ConfigurationManager.AppSettings["BuySellAnalyzer_PercChangeForMarketDirection"]);
FileTracing.TraceOut("percChangeForMarketDirection = " + percChangeForMarketDirection);
double minProfitPerc = double.Parse(ConfigurationManager.AppSettings["BuySellAnalyzer_MinProfitPerc"]);
FileTracing.TraceOut("minProfitPerc = " + minProfitPerc);
double stopLossPerc = double.Parse(ConfigurationManager.AppSettings["BuySellAnalyzer_StopLossPerc"]);
FileTracing.TraceOut("stopLossPerc = " + stopLossPerc);
int mock = int.Parse(ConfigurationManager.AppSettings["BuySellAnalyzer_MOCK"]);
if (mock == 1) iciciDirectAccount.MOCK = true;
else if (mock == 0) iciciDirectAccount.MOCK = false;
FileTracing.TraceOut("MOCK = " + iciciDirectAccount.MOCK);
bool allowShort = ConfigurationManager.AppSettings["BuySellAnalyzer_LongOrShort"] == "S";
bool allowLong = !allowShort;
FileTracing.TraceOut("allowShort = " + allowShort);
FileTracing.TraceOut("allowLong = " + allowLong);

Order initialOrder = null;
{
    string str_BuyPos = ConfigurationManager.AppSettings["BuySellAnalyzer_InitialOrder_OrderPosition"];
    double db_Price = -1;
    if (double.TryParse(ConfigurationManager.AppSettings["BuySellAnalyzer_InitialOrder_OrderPrice"], out db_Price) &&
        (!string.IsNullOrEmpty(str_BuyPos)))
    {
        Position position = (Position)Enum.Parse(typeof(Position), str_BuyPos);
        initialOrder = new Order(position, db_Price);
    }
    else
    {
        initialOrder = new Order();
    }
}
FileTracing.TraceOut("InitialOrder = " + initialOrder);
*/
